package com.example.okhttputils.com.utils.base.interfaces;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * file description
 * Created by gsc on 2019/8/27.
 */
public class OkHttpImp implements IHttp {


    private String TAG = "OkHttpImp";
    private static volatile Object mObject = new Object();
    private static volatile OkHttpImp mOkHttpImp;

    private OkHttpClient mOkHttpClient;


    private OkHttpImp() {
        if (mOkHttpClient == null) {
            mOkHttpClient = new OkHttpClient();
        }

    }

    public static OkHttpImp getInstance() {
        if (mOkHttpImp == null) {
            synchronized (mObject) {
                mOkHttpImp = new OkHttpImp();
            }
        }
        return mOkHttpImp;
    }

    private Handler mHandler;

    protected void setHandler(Handler handler) {
        mHandler = handler;

    }

    @Override
    public void doGet(String url, Map<String, String> params, final ResponseCallBack responseCallBack) {
        Log.e(TAG, "----" + mOkHttpClient.toString());
        if (params != null) {
            url = attachHttpGetParams(url, (HashMap) params);
        }
        Request request = new Request.Builder().url(url)
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                if (mHandler != null) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            responseCallBack.onFail(e.getMessage());
                        }
                    });
                }

            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                final String msg = response.body().string();

                if (mHandler != null) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            responseCallBack.onSuccessFully(msg);
                        }
                    });
                }

            }

        });

    }

    @Override
    public void doPost(String url, Map<String, String> prams, final ResponseCallBack responseCallBack) {
        FormBody.Builder body = new FormBody.Builder();
        if (prams != null) {
            for (Map.Entry<String, String> p : prams.entrySet()) {
                body.add(p.getKey(), p.getValue());
            }
        }
        Request request = new Request.Builder().url(url).post(body.build())
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                if (mHandler != null) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            responseCallBack.onFail(e.getMessage());
                        }
                    });
                }

            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final String msg = response.body().string();
                if (mHandler != null) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            responseCallBack.onSuccessFully(msg);
                        }
                    });
                }
            }
        });
    }


    @Override
    public void downLoadImage(String url, final ResponseCallBack responseCallBack) {


        Request request = new Request.Builder().url(url)
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                if (mHandler != null) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            responseCallBack.onFail(e.getMessage());
                            Log.e(TAG, "get msg: error" + e.getMessage());

                        }
                    });
                }

            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                final InputStream msg = response.body().byteStream();
                Log.e(TAG, "get msg:" + msg.toString());
                final Bitmap bitmap = BitmapFactory.decodeStream(msg);
                Log.e(TAG, "change to bitmap:" + bitmap.toString());
                Log.i(TAG, "onResponse: mahnder:" + mHandler.toString());
                if (mHandler != null) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            responseCallBack.onSuccessFully(bitmap);
                        }
                    });
                }

            }
        });

    }

    /**
     * 为HttpGet 的 url 方便的添加多个name value 参数。
     *
     * @param url
     * @param params
     *
     * @return
     */
    public static String attachHttpGetParams(String url, HashMap params) {

        Iterator<String> keys = params.keySet().iterator();
        Iterator<String> values = params.values().iterator();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("?");

        for (int i = 0; i < params.size(); i++) {
            String value = null;
            try {
                value = URLEncoder.encode(values.next(), "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }

            stringBuffer.append(keys.next() + "=" + value);
            if (i != params.size() - 1) {
                stringBuffer.append("&");
            }

        }

        return url + stringBuffer.toString();
    }

    @Override
    public void doPostJson(String url, String json, final ResponseCallBack callBack) {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        byte[] postData = new byte[0];
        if (json != null) {
            try {
                postData = json.getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        RequestBody body = RequestBody.create(JSON, postData);
        Request request = new Request.Builder().url(url).post(body)
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                if (mHandler != null) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callBack.onFail(e.getMessage());
                        }
                    });
                }

            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final String msg = response.body().string();
                if (mHandler != null) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callBack.onSuccessFully(msg);
                        }
                    });
                }
            }
        });
    }
}
